local blaze = require "blaze"
local app = require "app"
local game = require "club.threecard.jacksorbetter"
local consts = game.util.consts

local M = {}

M.state = {
    current_win = 0, -- 当前即将赢取的钱
    cards = { 0, 0, 0, 0, 0 }, -- 所有的手牌
    phase = consts.PHASE_IDLE,
    left_time = 0,
    rank_class = -1
}

M.getters = {
    phase_tip = function(state)
        local key = "phase tip" .. state.phase
        if app.i18n.exists(key) then
            return app.i18n.text(key)
        end
        return ""
    end,

    -- 获取一个值，表示当前是否为需要挑选扑克牌的阶段
    is_picking_phase = function(state)
        return state.phase == consts.PHASE_DEAL 
            or state.phase == consts.PHASE_PICK
    end
}

M.mutations = {
    exit_game = function(store, state)
        state.cards = { 0, 0, 0, 0, 0 }
        state.phase = consts.PHASE_IDLE

        store.emit("重置状态")
        store.emit("阶段变更")
    end,

    set_current_win = function(store, state, args)
        state.current_win = args.current
        store.emit("奖励变更", args)
    end,

    set_phase = function(store, state, args)
        state.phase = args.phase
        store.emit("阶段变更")
    end,

    deal = function(store, state, args)
        if state.phase == consts.PHASE_WIN or state.phase == consts.PHASE_LOSE then
            state.phase = consts.PHASE_IDLE
        else
            assert(state.phase == consts.PHASE_IDLE)
        end
        local player = blaze.kbe.player()
        if not player then
            return false
        end
        player:bet(app.store.bet_amounts.state.amount)
        return true
    end,

    hold = function(store, state, args)
        assert(state.phase == consts.PHASE_DEAL)
        local ids = args
        local player = blaze.kbe.player()
        if not player then
            return false
        end
        player:hold(ids)
        return true
    end,

    double = function(store, state, args)
        local player = blaze.kbe.player()
        if not player then
            return false
        end
        player:double()
        return true
    end,

    on_reveal = function(store, state, args)
        state.cards = args.card_ids
        state.rank_class = args.rank_class
        if state.phase == consts.PHASE_IDLE then
            store.emit("游戏开始")
        elseif state.phase == consts.PHASE_DEAL then
            store.emit("开局发牌")
        elseif state.phase == consts.PHASE_SETTLE then
            store.emit("结算亮牌")
        elseif state.phase == consts.PHASE_PICK then
            store.emit("赌博选牌")
        elseif state.phase == consts.PHASE_PICKED then
            store.emit("赌博亮牌")
        end
    end,

    on_settle = function(store, state, args)
        store.emit("最终结算", args)
    end
}

return M